/* ################### 地区js显示开始  ######################  */
function initArea() {
    //获取地区信息
    $.getJSON(PurchaseAppConfig.Domain + "/area/readLocationFromCookie.action" + "?rd" + Math.random(), function(result) {
        var locationId = result.locationId;
        var location = result.location;
        $("#hiddenLocationId").val(locationId);
        $("#hiddenLocation").val(location);

//        setArea();
    });

}

function setArea() {
    setAddress();
    if ($("#ids").val() != null && $("#ids").val() != "" && $("#hiddenLocationId").val() != null && $("#hiddenLocationId").val() != "") {
        var ss = $("#hiddenLocationId").val().split("-");
        provinceId = ss[0];
        cityId = ss[1];
        countyId = ss[2];
        if ($("#province").html() == null || $.trim($("#province").html()) == "") findProvinces(provinceId);
        if ($("#city").html() == null || $.trim($("#city").html()) == "") findCitys(provinceId, cityId);
        if ($("#county").html() == null || $.trim($("#county").html()) == "") findCountys(cityId, countyId);
    }
    //获取库存状态
    getStoreState();
}

//设置地区
function setAddress() {
    var location = $("#hiddenLocation").val();
    if (location != null && location != "") {
        var province = location.substring(0, 2); ;
        if (province == "黑龙" || province == "内蒙") {
            province = location.substring(0, 3);
        }
        $("#location").html(province);
        $("#location").attr("title", location);
    }
}

$("#province").change(function() {
    findCitys($(this).val(), 0);
});
$("#city").change(function() {
    findCountys($(this).val(), 0);
});
$("#county").change(function() {
    var provinceId = $("#province").val();
    var cityId = $("#city").val();
    var countyId = $("#county").val();
    var provinceName = $("#province").find("option:selected").text();
    var cityName = $("#city").find("option:selected").text();
    var countyName = $("#county").find("option:selected").text();
    var locationId = provinceId + "-" + cityId + "-" + countyId;
    var location = provinceName + cityName + countyName;
    $("#hiddenLocationId").val(locationId);
    $("#hiddenLocation").val(location);
    $("#inventory-dialog").hide();

    setAddress();
    getStoreState();
});

//得到库存
function getStoreState() {
    var locationId = $("#hiddenLocationId").val();
    var ids = $("#ids").val();
    var outSkus = $("#outSkus").val();
    if (locationId != null && locationId != "" && ids != null && ids != "") {
        $.getJSON(PurchaseAppConfig.Domain + "/area/querySkusStockState.action?locationId=" + locationId + "&ids=" + ids + "&rd" + Math.random(), function(result) {
            var states = result.areaStockStateInfos;
            $(".p-inventory").each(function() {
                var stockClass = $(this).attr("class");
                var ss = stockClass.split("-");
                var id = ss[ss.length - 1];
                if (states != null) {
                    for (var i = 0; i < states.length; i++) {
                        var state = states[i];
                        if (state.skuId == id) {
                            var info;
                            switch (state.stockStateId) {
                                case 33: info = "现货"; break;
                                case 34: info = "无货"; break;
                                case 36: info = "可预订"; break;
                                case 39: info = "可预订"; break;
                                case 40: info = "可配货"; break;
                                default: info = "无货";
                            }
                            //--如果订单返回到购物车,实际商品是无货,则把库存状态强制设置为无货
                            if (outSkus.indexOf(id) >= 0) {
                                info = "无货";
                            }
                            $(this).html(info);
                            $("#notify-" + id).remove();
                            //无货商品处理
                            if (info == "无货") {
                                var remove = $(this).siblings(".p-remove").children(".cart-remove");
                                //到货通知
                                var notify = "<span id='notify-" + id + "'><a class='cart-notify' href='javascript:void(0);' onclick='productNotify(this," + id + ")'>到货通知</a>&nbsp;|&nbsp;</span>";
                                remove.before(notify);
                            }
                        }
                    }
                }
            });
        });
    }
}

//查找省份
function findProvinces(defaultValue) {
    findAreas("findProvinces", "province", 0, defaultValue);
}

//查找城市
function findCitys(fid, defaultValue) {
    if (fid != null && fid != 0) {
        findAreas("findCitys", "city", fid, defaultValue);
        $("#county").html("");
    }
}

//查找县市
function findCountys(fid, defaultValue) {
    if (fid != null && fid != 0) {
        findAreas("findCountys", "county", fid, defaultValue);
    }
}

function findAreas(method, id, fid, defaultValue) {
    $.getJSON(PurchaseAppConfig.Domain + "/area/" + method + ".action?fid=" + fid + "&rd" + Math.random(), function(data) {
        var str = "";
        if (data.areas != null) {
            for (var i = 0; i < data.areas.length; i++) {
                var selected = "";
                if (data.areas[i].id == defaultValue) {
                    selected = " selected ";
                }
                str += "<option value=" + data.areas[i].id + selected + ">" + data.areas[i].name + "</option>";
            }
        }
        $("#" + id).html(str);
    });
}
/* ################### 地区js显示结束  ######################  */
function readPinCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return arr[2]; return null;
}
var loguri = "http://csc.jd.com/log.ashx?type1=$type1$&type2=$type2$&data=$data$&pin=$pin$&referrer=$referrer$&jinfo=$jinfo$&callback=?";
callback1 = function(data) {
    ;
}
log = function(type1, type2, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) {
    var data = '';
    for (i = 2; i < arguments.length; i++) {
        data = data + arguments[i] + '|||';
    }
    var url = loguri.replace(/\$type1\$/, escape(type1));
    url = url.replace(/\$type2\$/, escape(type2));
    url = url.replace(/\$data\$/, escape(data));
    url = url.replace(/\$pin\$/, escape(decodeURIComponent(readPinCookie("pin"))));
    url = url.replace(/\$referrer\$/, escape(document.referrer));
    url = url.replace(/\$jinfo\$/, escape(''));
    $.getJSON(
            url,
            callback1
        );
}
function setCookie(name, value, date) {
    var Days = date;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;domain=.jd.com";
}
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]); return null;
}
function reClick(type2, pwid, sku, num) {
    name = "reWids" + type2;
    reWids = getCookie(name);
    if (reWids != null) {
        reWids = reWids.toString();
        var pos = reWids.indexOf(sku);
        if (pos < 0) {
            reWids = reWids + "," + sku;
        }
    }
    else {
        reWids = sku;
    }
    setCookie(name, reWids, 6);

    sku = sku.split("#");
    log(3, type2, sku[0]);
    log('RC', 'CK', type2, pwid, sku[0], num);
}
function someOtherWare(element, ip, ids) {
    $.ajax({
        url: "http://simigoods.jd.com/GetRecommendWareCart.aspx",
        type: "get",
        dataType: "jsonp",
        data: "ip=" + ip + "&wids=" + ids,
        async: true,
        success: function(data) {
            var obj = {};
            var data = data["data"];
            if (data != null && data.length != 0) {
                obj.data = data;
                var html = "";
                var template_new_cart = '<ul class="clearfix">'+
                '{for item in data}'+
                '<li onclick=reClick("2","1","${item.id}","${item_index}")>' +
		        '<div class="p-img"><a href="${item.url}"><img width="130" height="130" src="${item.img}" alt="" /></a></div>' +
		        '<div class="p-name"><a href="${item.url}">${item.name}</a></div>' +
		        '<div class="p-price"><img src="http://price.360buyimg.com/gp${item.id},1.png" onerror="this.src=\'http://www.jd.com/images/no2.gif\'"></div>' +
		        '<div class="p-btn"><a href="javascript:addSkuToCartReBuy(${item.id},1,1,0,0);" class="btn"><span class="btn-icon"></span><span class="btn-text">\u52A0\u5165\u8D2D\u7269\u8F66</span></a></div>' +
	            '</li>' +
	            '{/for}' +
                '</ul><div id="recommend-left"></div><div id="recommend-rigth"></div>';
                html = template_new_cart.process(obj);
                element.html(html);
                $("#recommend-products").show();
                $("#c-tabs").show();
                $(function() {
                    $("#some-buy").jdMarquee({
                        deriction: "left",
                        auto: true,
                        width: 878,
                        height: 245,
                        step: 4,
                        delay: 10,
                        control: true,
                        speed: 4,
                        _front: "#recommend-rigth",
                        _back: "#recommend-left"
                    });
                });
                log('R2', 'Show', data.length);
            } else {
                $("#recent-collection").attr("class", "cm fore1 curr");
            }
        }
    });
}
function moreRecent(element) {
    $.ajax({
        url: "http://t.jd.com/follow/followProductListByPurchase.action",
        type: "get",
        dataType: "jsonp",
        async: true,
        success: function(data) {
            if (data != null) {
                var obj = {};
                obj.data = data;
                var html = "";
                html = template_extra_cart.process(obj);
                element.html(html);
                if ($("#recommend-products").css("display") == "none") {
                    $("#recent-collection").attr("class", "cm fore1 curr");
                }
                $("#recent-collection").show();
                $("#c-tabs").show();
            }
        }
    });
}